
import { RouteComponentProps } from 'react-router-dom'
import React, { Component } from 'react'
import { Button, Card, Form, Input, Spin, message, Modal, Popconfirm } from "antd";
import UserInfo from '../../../../../types/UserInfo';
import { FormInstance } from 'antd/lib/form';
import UserType from '../../../../../types/UserType';
import { queryUserInfo, modifyUserInfo } from '../../../../../requests/Personal';
import { Store, ValidateErrorEntity } from 'rc-field-form/lib/interface'
import ButtonGroup from 'antd/lib/button/button-group';
import {getRes} from "../../../../../configFile";


interface IProps extends RouteComponentProps<{id: string }> { }
interface IState {
    userInfo: UserInfo,
    isLoading: boolean,                     //信息修改页面是否加载中
    passwordModifyModalVisible: boolean,    //修改密码的模态框是否为显示状态
}
export default class SpecificModifyUserInfo extends Component<IProps, IState> {
    //使用ref获取数据域
    formRef = React.createRef<FormInstance>()
    constructor(props: IProps) {
        super(props)
        this.state = {
            isLoading: true,
            userInfo: {
                ID: Number.parseInt(this.props.match.params.id),
                username: '',
                password: undefined,
                telephone: '',
                email: '',
                lastLoginTimestamp: -1,
                creationTimestamp: -1,
                userType: UserType.DEVICEADMIN
            },
            passwordModifyModalVisible: false
        }
    }

    /*表单样式*/
    layout = {
        labelCol: { span: 4 },
        wrapperCol: { span: 16 },
    };
    tailLayout = {
        wrapperCol: { offset: 4 },
    };
    /*模态框表单样式*/
    modalLayout = {
        labelCol: { span: 6 },
        wrapperCol: { span: 16 },
    };
    modalTailLayout = {
        wrapperCol: { offset: 6 },
    };

    async componentDidMount() {
        //从redux中拿用户id
        let res = getRes(await queryUserInfo(this.state.userInfo.ID))
        console.log(res)
        this.setState({
            ...this.state,
            userInfo: res.data,
            isLoading: false
        })
        //实例不为空
        if (this.formRef.current)
            this.formRef.current.setFieldsValue(this.state.userInfo)
    }

    //输入合法函数
    onFinish: (values: Store) => void = async values => {

        try {
            this.setState({ isLoading: true })
            const res = getRes(await modifyUserInfo({ ...values, ID: this.state.userInfo.ID}))
            if (res.message === 'modifyUserInfoSuccess') {
                message.success("提交成功")
            } else {
                message.error("提交失败")
            }
            this.setState({ isLoading: false })
        } catch (err) {
            message.error(err.toString())
        }
    }
    //输入非法函数
    onFinishFailed = (errorInfo: ValidateErrorEntity) => {
        message.error(errorInfo.errorFields[0].errors[0]);
    };

    /* 修改密码模态框相关函数 */
    //显示模态框
    showModal = () => {
        this.setState({
            passwordModifyModalVisible: true,
        });
    };
    //关闭模态框
    passwordModifyHandleCancel = (e: React.MouseEvent<HTMLElement, MouseEvent>) => {
        this.setState({
            passwordModifyModalVisible: false,
        });
    };
    //模态框提交成功
    onModalFinish: (values: Store) => void = async values => {
        try {
            this.setState({ isLoading: true })
            const res = getRes(await modifyUserInfo({ password: values.password, ID: this.state.userInfo.ID}))

            if (res.message === 'modifyUserInfoSuccess') {
                message.success("修改成功")
            } else {
                message.error("修改失败")
            }
            this.setState({ isLoading: false })
        } catch (err) {
            message.error(err.toString())
        }
        //关闭模态框
        this.setState({
            passwordModifyModalVisible: false,
        });
    }
    //模态框提交失败
    onModalFinishFailed = (errorInfo: ValidateErrorEntity) => {
        message.error(errorInfo.errorFields[0].errors[0]);
    };

    //放弃修改
    modifyAbort = () => {
        this.props.history.goBack()
    }


    render() {
        return (
            <div>
                <Spin size='large' spinning={this.state.isLoading}>
                    <Card
                        title={<span style={{ fontWeight: 'bold' }}>个人信息管理</span>}
                        bordered={true}
                        extra={
                            <ButtonGroup>
                                <Button type="primary" onClick={this.showModal}>修改密码</Button>
                                <Popconfirm
                                    placement="topRight"
                                    title='确定放弃更改吗？'
                                    onConfirm={this.modifyAbort}
                                    okText="确定"
                                    cancelText="取消"
                                >
                                    <Button danger>放弃更改</Button>
                                </Popconfirm>
                            </ButtonGroup>}>
                        <Form
                            onFinishFailed={this.onFinishFailed}
                            onFinish={this.onFinish}
                            ref={this.formRef}
                            {...this.layout}
                            name="personal"
                        >
                            <Form.Item
                                label="用户名"
                                name="username"
                                rules={[{ required: true, message: '用户名不能为空' }]}
                            >
                                <Input />
                            </Form.Item>

                            <Form.Item
                                label="邮箱"
                                name="email"
                                rules={[{ required: true,message:'请正确填写邮箱格式',type:'email' }]}
                            >
                                <Input />
                            </Form.Item>

                            <Form.Item
                                label="电话"
                                name="telephone"
                                rules={[{ required: true, message: '电话不能为空' },
                                    ({ getFieldValue }) => ({
                                        validator(rule, value) {
                                            var phoneReg = /^[1][3,4,5,7,8][0-9]{9}$/
                                            if (!value || phoneReg.test(value)) {
                                                return Promise.resolve();
                                            }
                                            return Promise.reject('请输入正确电话号码');
                                        },
                                    }),
                                ]}
                            >
                                <Input />
                            </Form.Item>

                            <Form.Item {...this.tailLayout}>
                                <Button type="primary" htmlType="submit" size="large">
                                    确认修改
                                    </Button>
                            </Form.Item>
                        </Form>
                    </Card>
                </Spin>

                {/* 修改密码模态框 */}
                <Modal
                    title="修改密码"
                    visible={this.state.passwordModifyModalVisible}
                    onCancel={this.passwordModifyHandleCancel}
                    footer={null}
                >
                    <Spin spinning={this.state.isLoading}>
                        <Form
                            onFinishFailed={this.onModalFinishFailed}
                            onFinish={this.onModalFinish}
                            ref={this.formRef}
                            {...this.modalLayout}
                            name="passwordModify"
                            hideRequiredMark
                        >

                            <Form.Item
                                name="password"
                                label="请输入新密码"
                                rules={[
                                    {
                                        required: true,
                                        message: '密码必填',
                                    },
                                ]}
                                hasFeedback
                            >
                                <Input.Password />
                            </Form.Item>

                            <Form.Item
                                name="confirm"
                                label="确认密码"
                                dependencies={['password']}
                                hasFeedback={true}
                                rules={[
                                    {
                                        required: true,
                                        message: '确认密码必填',
                                    },
                                    ({ getFieldValue }) => ({
                                        validator(rule, value) {
                                            if (!value || getFieldValue('password') === value) {
                                                return Promise.resolve();
                                            }

                                            return Promise.reject('两次密码输入不一致！');
                                        },
                                    }),
                                ]}
                            >
                                <Input.Password />
                            </Form.Item>
                            <Form.Item {...this.modalTailLayout}>
                                <Button type="primary" htmlType="submit">
                                    确认修改
                            </Button>
                            </Form.Item>
                        </Form>
                    </Spin>
                </Modal>
            </div>

        )
    }
}